package com.swsc.ai.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author QF
 * @date 2023/10/20 15:32
 * @describe
 */
public class DateUtil {

    /**
     * 获取最近工作日
     * @param date
     * @return
     */
    public static LocalDate getWork(LocalDate date){
        // 判断年份
        int year = date.getYear();
        try {
            // 读取 JSON 文件内容
            String jsonContent = FileUtil.readUtf8String("holiday/holiday-" + year + ".json");
            JSONObject jsonObject = JSONUtil.parseObj(jsonContent);
            JSONObject holidayList = jsonObject.getJSONObject("holiday");
            JSONObject holiday = holidayList.getJSONObject(date.format(DateTimeFormatter.ofPattern("MM-dd")));
            boolean isNotHoliday = !isWeek(date) && (holiday == null || !holiday.getBool("holiday"));
            if (isNotHoliday){
                return date;
            }
            return getWork(date.minusDays(1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Boolean isWeek(LocalDate date){
        if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取dt的前n天的日期 如dt = "20231101", n = 1 则return "20231031"
     * @param n
     * @return
     */
    public static String getBeforeNDay(String dt, long n) {
        return LocalDate.parse(dt, DateTimeFormatter.ofPattern("yyyyMMdd")).minusDays(n).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }
}
